

from datetime import datetime, timedelta

from pymysql.constants.ER import NO


class pipelineJobsProjects():

    def jobsList(project):
        # list jobs for the project page =1 not 0 ,per_page default 20  or more
        jobs = project.jobs.list(page=1, per_page=120)

        jobsAll = []
        for job in jobs:
            # print(job)
            # format time for finished
            finished = job.finished_at
            # print(job)
            
            if finished == None:
              pass
            else:
              UTC_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
              utcTime = datetime.strptime(finished, UTC_FORMAT)
              utcDate = utcTime + timedelta(hours=8)
              local = "%Y-%m-%d %H:%M:%S"
              finished = datetime.strftime(utcDate,local)
            # format time for create_at
            createdTime = job.created_at
            if createdTime == None:
              pass
            else:
              UTC_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
              utcTime = datetime.strptime(createdTime, UTC_FORMAT)
              utcDate = utcTime + timedelta(hours=8)
              local = "%Y-%m-%d %H:%M:%S"
              createdTime = datetime.strftime(utcDate,local)


            # print(finished)
            jobsJson = {"id": job.id, "status": job.status, "ref": job.ref,
                        "created_at": createdTime,"finished_at":finished,"name":job.name,"stage":job.stage, "coverage":job.coverage, "duration":job.duration,"user": job.user["username"], "user_created_at": job.user["created_at"], "commit_id": job.commit["id"], "commit_message": job.commit["message"],
                        "commit_created_at": job.commit["created_at"], "commit_committer_name": job.commit["committer_name"],"short_id":job.commit["short_id"], "pipeline_id": job.pipeline["id"], "pipeline_project_id": job.pipeline["project_id"],
                        "pipeline_status": job.pipeline["status"]}

            jobsAll.append(jobsJson)
        # print(jobsAll)

        return jobsAll

    def jobsOneSingle(project, jobid):
        try:
            # a single job id project
            singlejob = project.jobs.get(jobid)
            return singlejob
        except Exception as e:
            return "job id is not exist", e

    def jobsPaly(project, jobid):
      # get a single job
        getsinglejob = project.jobs.get(jobid).attributes
      # obain runner not none retry job
        if getsinglejob['runner'] != None:
            lazyjob = project.jobs.get(jobid, lazy=True)
            lazyjob.retry()
        else:
            print("None")
